package com.gexiaobao.pigeon.ui.auction

import android.content.res.ColorStateList
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.Auction
import com.gexiaobao.pigeon.app.model.bean.Banner
import com.gexiaobao.pigeon.app.model.bean.TodayEnd
import com.gexiaobao.pigeon.app.model.bean.TomorrowEnd
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.databinding.FragmentMainAuctionBinding
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.auction.fragment.FragmentClosingAuction
import com.gexiaobao.pigeon.ui.auction.fragment.FragmentSpecialAuction
import com.gexiaobao.pigeon.ui.auction.fragment.FragmentTomorrowEnd
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.google.android.material.tabs.TabLayout
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity


/**
 * @Author      : hxw
 * @Date        : 2024/11/7 11:16
 * @Describe    : 拍卖
 */
class FragmentAuction : BaseFragment<AuctionViewModel, FragmentMainAuctionBinding>() {

    private var auctions: ArrayList<Auction> = arrayListOf()
    private var todayEnds: ArrayList<TodayEnd> = arrayListOf()
    private var tomorrowEnds: ArrayList<TomorrowEnd> = arrayListOf()

    private var sharedViewModel: SharedViewModel? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        sharedViewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
        return super.onCreateView(inflater, container, savedInstanceState)
    }

    override fun initView(savedInstanceState: Bundle?) {
        showLoading(getString(R.string.loading))
        mViewModel.getAuctionHome()
        mViewModel.createAuctionUserConf()
        initTabLayout()
        mDatabind.swipeRefreshLayout.init {
            mViewModel.getAuctionHome()
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取app拍卖商品详情 */
        mViewModel.auctionHomeResult.observe(viewLifecycleOwner) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) {
                mDatabind.swipeRefreshLayout.isRefreshing = false
            }
            initBanner(it.banners)
            auctions.clear()
            auctions.addAll(it.auctions)
            todayEnds.clear()
            todayEnds.addAll(it.todayEnds)
            tomorrowEnds.clear()
            tomorrowEnds.addAll(it.tomorrowEnds)
            sharedViewModel?.setAuctionsData(auctions)
            sharedViewModel?.setTodayData(todayEnds)
            sharedViewModel?.setTomorrowData(tomorrowEnds)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.tvRightMenu, mDatabind.tvEnd, mDatabind.tvTomorrowEnd, mDatabind.tvSubject) {
            when (it) {
                mDatabind.tvSubject -> startActivity<ActivityAuctionDetail>("index" to 2)
                mDatabind.tvTomorrowEnd -> startActivity<ActivityAuctionDetail>("index" to 1)
                mDatabind.tvEnd -> startActivity<ActivityAuctionDetail>("index" to 0)
                mDatabind.tvRightMenu -> startActivity<ActivityAuctionHelp>()
            }
        }
    }

    private fun initBanner(banners: ArrayList<Banner>) {
        val imageUrls = ArrayList<String>()
        if (banners.isNotEmpty()) {
            banners.forEach {
                imageUrls.add(it.img)
            }
            mDatabind.bannerAuction.isVisible = true
            mDatabind.viewBg.isVisible = true
        } else {
            mDatabind.bannerAuction.isVisible = false
            mDatabind.viewBg.isVisible = false
        }
        mDatabind.bannerAuction.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(imageUrls), false)//设置banner的适配器,是否支持无限循环
            .setIndicator(CircleIndicator(context))
            .isAutoLoop(true)
            .setLoopTime(3000).setOnBannerListener { data, _ ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast("图片资源获取失败")
                    return@setOnBannerListener
                }
            }
        mDatabind.bannerAuction.setBannerRound(20F)
    }

    private fun initTabLayout() {
        mDatabind.tabLayout.tabRippleColor = ColorStateList.valueOf(ContextCompat.getColor(requireContext(), android.R.color.transparent))
        val tab1 = mDatabind.tabLayout.newTab().setText(getString(R.string.Closing_auction_today))
        val tab2 = mDatabind.tabLayout.newTab().setText(getString(R.string.tomorrow_end))
        val tab3 = mDatabind.tabLayout.newTab().setText(getString(R.string.auction_subject))
        mDatabind.tabLayout.addTab(tab1)
        mDatabind.tabLayout.addTab(tab2)
        mDatabind.tabLayout.addTab(tab3)

        mDatabind.tabLayout.addOnTabSelectedListener(object : TabLayout.BaseOnTabSelectedListener<TabLayout.Tab> {
            override fun onTabReselected(p0: TabLayout.Tab) {}
            override fun onTabUnselected(p0: TabLayout.Tab) {}
            override fun onTabSelected(p0: TabLayout.Tab) {
                replaceFragments(p0.position)
            }
        })
        replaceFragments(0)
    }

    private fun replaceFragments(position: Int) {
        childFragmentManager.beginTransaction().apply {
            when (position) {
                0 -> replace(R.id.frameLayout, FragmentClosingAuction.newInstance())
                1 -> replace(R.id.frameLayout, FragmentTomorrowEnd.newInstance())
                2 -> replace(R.id.frameLayout, FragmentSpecialAuction.newInstance())
            }
        }.commitAllowingStateLoss()
    }
}